//
//  pinglunVC.m
//  K-Music
//
//  Created by 林杰良 on 16/1/8.
//  Copyright © 2016年 CHUN. All rights reserved.
//

#import "pinglunVC.h"

@interface pinglunVC ()<UITableViewDataSource,UITableViewDelegate>{
    
    UITableView*PLTableView;
    
    NSMutableArray*pinglunData;
    
    UITextField * searchTF;
}

@end

@implementation pinglunVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor=[UIColor whiteColor];
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"back" highIcon:@"back" target:self action:@selector(back_back)];
    self.navigationItem.title = @"评论";
    
    [self tapView];
    
    [self creatUI];
    
    [self downloadTheGuiBinData];

}

- (void)back_back
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark---pinglun{

-(void)downloadTheGuiBinData{
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];

    NSString *intactURL = [NSString stringWithFormat:@"http://112.74.72.48:8080/api/comments?page=0&size=20&sort=createdDate,DESC"];
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary*dic=[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSLog(@"成功评论GET --> %@", dic);
        
        pinglunData=[NSMutableArray array];
        
        NSLog(@"resultCode:%@",dic[@"resultCode"]);
        NSArray*content=dic[@"body"][@"content"];
        
        for (NSDictionary *guibin_Datas in content) {
            PingLun*aa=[[PingLun alloc]init];
            
            aa.aid=guibin_Datas[@"id"];
            aa.userId=guibin_Datas[@"userId"];
            aa.recordId=guibin_Datas[@"recordId"];
            aa.content=guibin_Datas[@"content"];
            aa.createdBy=guibin_Datas[@"createdBy"];
            aa.createdDate=guibin_Datas[@"createdDate"];
            aa.lastModifiedBy=guibin_Datas[@"lastModifiedBy"];
            aa.lastModifiedDate=guibin_Datas[@"lastModifiedDate"];
            aa.createdUserNickName = guibin_Datas[@"createdUserNickName"];
            aa.createdUserAvatar = guibin_Datas[@"createdUserAvatar"];
            [aa fixedString];
            [pinglunData addObject:aa];
            
        }
        
        [PLTableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        
    }];
    
}

-(void)creatUI{
    
    PLTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-114)];
    PLTableView.delegate=self;
    PLTableView.dataSource=self;
//    PLTableView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"tableview"]];
    PLTableView.backgroundColor = RGB(128, 104, 84);
    [self.view addSubview: PLTableView];
    
    UIView*chioseView=[[UIView alloc]init];
    chioseView.frame=CGRectMake(0,HEIGHT-114, WIDTH, 50);
    chioseView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:chioseView];
    
    UIView*TF=[[UIView alloc]init];
    
    TF.backgroundColor=RGB(238, 238, 238);
    
    TF.frame=CGRectMake(5, 5, WIDTH-60, 40);
    
    TF.layer.masksToBounds=YES;
    TF.layer.borderWidth=2.0F;
    TF.layer.borderColor=[UIColor whiteColor].CGColor;
    [TF.layer setCornerRadius:20];
    
    [chioseView addSubview:TF];
    
    UIButton * SearchAction=[UIButton buttonWithType:UIButtonTypeCustom];
    SearchAction.frame=CGRectMake(TF.frame.origin.x+TF.frame.size.width+2, 5, 50, 40);
    [SearchAction setTitle:@"发送" forState:UIControlStateNormal];
    [SearchAction setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    SearchAction.titleLabel.font=[UIFont systemFontOfSize:14.0f];
    [SearchAction addTarget:self action:@selector(comments) forControlEvents:UIControlEventTouchUpInside];
    [chioseView addSubview:SearchAction];
    
    UIImageView*image=[[UIImageView alloc]init];
    image.frame=CGRectMake(10, 10, 25, 30);
    image.image=[UIImage imageNamed:@""];
    [TF addSubview:image];
    
    searchTF=[[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(image.frame)+10, 0, WIDTH-120, 40)];
    searchTF.backgroundColor=[UIColor clearColor];
    searchTF.clearButtonMode=UITextFieldViewModeAlways;
    searchTF.keyboardType = UIKeyboardTypeDefault;
    searchTF.returnKeyType =UIReturnKeySearch;
    searchTF.clearsOnBeginEditing = YES;
    searchTF.keyboardAppearance=UIKeyboardAppearanceDefault;
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    searchTF.text = @"输入评论";
    [TF addSubview: searchTF];
    
}

- (void)comments
{
    [self CancelkeyBoard];
    if (searchTF.text.length ==0 ) {
        [MBProgressHUD showErrorWithStatus:@"输入不能为空！" toView:self.view];
    }
    else
    {
        AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
        
        NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
        
        manager.requestSerializer =[AFJSONRequestSerializer serializer];
        
        [manager.requestSerializer setValue:@"application/json"
                         forHTTPHeaderField:@"Accept"];
        [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                         forHTTPHeaderField:@"Authorization"];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        NSString*infoStr11=[NSString stringWithFormat:@"/api/comments"];
        
        NSString *intactURL = [MyBaseUrl stringByAppendingString:infoStr11];
        
        NSDictionary * submit = @{@"content":searchTF.text,@"recordId":@"8",@"userId":@"3"};
        
        [manager POST:intactURL parameters:submit success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSDictionary * result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
             
             NSLog(@"================:%@",result);
             NSDictionary * body = [result objectForKey:@"body"];
             
             NSString * abc = [NSString stringWithFormat:@"以收录评论 ID- %@ - 意见 - %@ -",[body objectForKey:@"createdBy"],[body objectForKey:@"content"]];
             
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:abc delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//             [alert show];
             
         }failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             NSLog(@"%@", error);
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"服务器错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
             [alert show];
         }];
    }
}

//收键盘手势
- (void)tapView
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(CancelkeyBoard)];
    [self.view addGestureRecognizer:tap];
}

- (void)CancelkeyBoard
{
    [searchTF resignFirstResponder];
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return pinglunData.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString*inf=@"pinglunCell";
    
    pinglunCell*cell=[tableView  dequeueReusableCellWithIdentifier:inf];
    if (cell == nil) {
        
        cell = [[[NSBundle mainBundle]loadNibNamed:@"pinglunCell" owner:self options:nil ] firstObject];
        
    }
    PingLun*pl=[[PingLun alloc]init];
    pl=pinglunData[indexPath.row];
    [cell.imgStr sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",pl.createdUserAvatar]]];
    cell.imgStr.layer.cornerRadius= cell.imgStr.width/2;
    cell.imgStr.layer.masksToBounds = YES;
    
    cell.nameStr.text=[NSString stringWithFormat:@"%@",pl.createdUserNickName];
    
    cell.infoStr.text=[NSString stringWithFormat:@"%@",pl.content];
    
    cell.timeStr.text= [NSString stringWithFormat:@"%@",pl.createdDate];
    
    cell.backgroundColor=[UIColor clearColor];
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
